
package xj.app;

import static xj.app.BaseApplicationFrame.logInfo;

public class AutoSave extends Thread {

  private AutoSaveListener listener;

  private static int interval = 300; // 300 seconds
  //private static int interval = 30; // 30 seconds, for testing 
  
  /**
   * Starts the auto save thread.
   */
  public AutoSave(AutoSaveListener listener) {
    this(listener, 30);
  }

  public AutoSave(AutoSaveListener listener, int v) {
    super("----thread: autosave----");
    this.listener = listener;
    interval = v; 
    setDaemon(true);
    start();

    //System.out.println("Start AutoSave " + listener.getClass().getName());
    logInfo("Start AutoSave");
  }

  /**
   * Returns the intervale, in seconds, between each save.
   */
  public static int getInterval() {
    return interval;
  }

  /**
   * Sets the interval, in seconds, between each save.
   */

  public static void setInterval(int newInterval) {
    interval = newInterval;
  }

  @Override
  public void run() {
    //System.out.println("AutoSave @0");

    if (interval == 0)
      return;

    int delay = interval * 1000;

    while(true) {
      try {
        Thread.sleep(delay);
      }	catch(InterruptedException i) {
        return;
      }

      //System.out.println("AutoSave " + listener.getClass().getName());
      
      if (listener != null) { 
	listener.autoSaveAllDocuments();
      }

      if (interrupted())
        return;
    }
  }
  

}
